package com.suray.attendance.contacts.service.impl;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiV2DepartmentListsubRequest;
import com.dingtalk.api.response.OapiV2DepartmentListsubResponse;
import com.suray.attendance.common.dingding.service.DingAccessTokenService;
import com.suray.attendance.common.utils.LoggerUtil;
import com.suray.attendance.model.pojo.DeptInfo;
import com.suray.attendance.contacts.service.DingDeptService;
import com.taobao.api.ApiException;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: jianglinyu
 * @CreateTime: 2023-07-10  13:21
 * @Description: TODO
 * @Version: 1.0
 */
@CommonsLog
@Service
public class DingDeptServiceImpl implements DingDeptService {

    @Resource
    private DingAccessTokenService dingAccessTokenService;
    /**
     * @param pid   根id = 1
     * @description: 根据pid获取钉钉OA的部门第一层子部门的数据
     * @author: jianglinyu
     * @date: 2023/11/21 11:26
     * @return
     */
    @Override
    public List<DeptInfo> getDingDeptInfoFromDingDing(String accessToken,Long pid) {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
        OapiV2DepartmentListsubRequest req = new OapiV2DepartmentListsubRequest();
        req.setDeptId(pid);
        req.setLanguage("zh_CN");
        OapiV2DepartmentListsubResponse rsp = null;
        try {
            rsp = client.execute(req,accessToken);
            if(rsp.getErrcode()==0){
                // 获取获取数据成功
                List<OapiV2DepartmentListsubResponse.DeptBaseResponse> result = rsp.getResult();
                List<DeptInfo> deptInfoList ;
                return deptInfoList = result.stream().map(deptBaseResponse -> {
                    DeptInfo deptInfo = new DeptInfo();
                    deptInfo.setId(deptBaseResponse.getDeptId());
                    deptInfo.setPid(deptBaseResponse.getParentId());
                    deptInfo.setName(deptBaseResponse.getName());
                    deptInfo.setCreateTime(LocalDateTime.now());
                    return deptInfo;
                }).collect(Collectors.toList());
            }else {
                LoggerUtil.error("根据pid="+pid+"获取钉钉OA的子部门的数据出现异常"+rsp.getErrmsg(),DingDeptServiceImpl.class);
            }
        } catch (ApiException e) {
            e.printStackTrace();
            LoggerUtil.error("根据pid="+pid+"获取钉钉OA的子部门的数据出现异常",DingDeptServiceImpl.class);
            throw new RuntimeException("根据pid="+pid+"获取钉钉OA的子部门的数据出现异常");
        }
        return null;
    }
}